package com.hxh.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/9/7 10:42
 * 线程间的定制化通信
 */
public class ThreadDemo03 {

    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();
        new Thread(() -> {
           for (int i = 1; i <= 10; i++) {
               try {
                   shareResource.print5(i);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    shareResource.print10(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    shareResource.print15(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "CC").start();
    }
}

// 资源类
class ShareResource {
    private int flag = 1; // 标志位

    // 可重入锁
    private Lock lock = new ReentrantLock();

    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    // 打印 5 次
    public void print5(int loop) throws InterruptedException {
        lock.lock();
        try {
            while (flag != 1) {
                c1.await();
            }
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + "::" + i + ", 当前轮数: " + loop);
            }
            flag = 2;
            c2.signalAll();
        } finally {
            lock.unlock();
        }
    }

    // 打印 10 次
    public void print10(int loop) throws InterruptedException {
        lock.lock();
        try {
            while (flag != 2) {
                c2.await();
            }
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName() + "::" + i + ", 当前轮数: " + loop);
            }
            flag = 3;
            c3.signalAll();
        } finally {
            lock.unlock();
        }
    }

    // 打印 15 次
    public void print15(int loop) throws InterruptedException {
        lock.lock();
        try {
            while (flag != 3) {
                c3.await();
            }
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName() + "::" + i + ", 当前轮数: " + loop);
            }
            flag = 1;
            c1.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
